package com.sunday.android.fangdaifu.bukong.fragment.tab;


import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.sunday.android.fangdaifu.bukong.BaseApp;
import com.sunday.android.fangdaifu.bukong.R;
import com.sunday.android.fangdaifu.bukong.adapter.IndexWithHeadersAdapter;
import com.sunday.android.fangdaifu.bukong.entity.IndexItem;
import com.sunday.android.fangdaifu.bukong.entity.IndexProject;
import com.sunday.android.fangdaifu.bukong.entity.IndexTop;
import com.sunday.android.fangdaifu.bukong.http.ApiClient;
import com.sunday.android.fangdaifu.bukong.utils.LazyFragment;
import com.sunday.android.fangdaifu.bukong.utils.stickyheadersrecyclerview.StickyRecyclerHeadersDecoration;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.ToastUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * A simple {@link Fragment} subclass.
 * 首页
 */
public class IndexFragment extends LazyFragment {


    @Bind(R.id.recycler_view)
    RecyclerView recyclerView;
    @Bind(R.id.refresh_layout)
    SwipeRefreshLayout refreshLayout;
    @Bind(R.id.left_btn)
    ImageView leftBtn;
    @Bind(R.id.title_view)
    TextView titleView;

    private boolean isPrepared;
    private boolean mHasLoadedOnce;
    private long memberId;
    private IndexWithHeadersAdapter adapter;
    private StickyRecyclerHeadersDecoration headersDecor;

    private IndexTop indexTop;//首页头部报表和新闻列表
    private List<IndexProject> projectList = new ArrayList<>();//首页项目列表'

    public IndexFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_index, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        memberId = BaseApp.getInstance().getMemberId();
        initView();
        isPrepared = true;
        lazyLoad();
    }

    //初始化布局
    private void initView() {
        leftBtn.setVisibility(View.GONE);
        titleView.setText("首页");
        //设置列表数据和浮动header
        final LinearLayoutManager layoutManager = new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(layoutManager);
        List<IndexItem> list = new ArrayList<>();
        IndexItem indexItem;
        for (int i = 0; i < 10; i++) {
            indexItem = new IndexItem();
            indexItem.setHaveHeader(i == 0 ? false : true);
            list.add(indexItem);
        }
        adapter = new IndexWithHeadersAdapter(mContext,indexTop,projectList);
        recyclerView.setAdapter(adapter);
        headersDecor = new StickyRecyclerHeadersDecoration(adapter);
        recyclerView.addItemDecoration(headersDecor);
        refreshLayout.setColorSchemeResources(R.color.material_red, R.color.material_green,
                R.color.material_blue, R.color.material_yellow);
        recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                outRect.bottom = 1;
            }
        });
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                loading();
                aIndexCount();//首页top数据
                abIndexProjectList();//首页列表
            }
        });
    }

    //可见后加载数据
    @Override
    protected void lazyLoad() {
        if (!isPrepared || !isVisible || mHasLoadedOnce) {
            return;
        }
        mHasLoadedOnce = true;
        loading();
        aIndexCount();//首页top数据
        abIndexProjectList();//首页列表
    }

    private void aIndexCount() {
        Call<ResultDO<IndexTop>> call = ApiClient.getApiAdapter().AaIndexCount(memberId);
        call.enqueue(new Callback<ResultDO<IndexTop>>() {
            @Override
            public void onResponse(Call<ResultDO<IndexTop>> call, Response<ResultDO<IndexTop>> response) {
                if (response.body() == null || isFinish) {
                    return;
                }
                refreshLayout.setRefreshing(false);
                if (response.body().getCode() == 0 && response.body().getResult() != null) {
                    indexTop = response.body().getResult();
                    adapter.refresh(indexTop);
                } else {
                    ToastUtils.showToast(mContext, response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO<IndexTop>> call, Throwable t) {
                if (isFinish) {
                    return;
                }
                refreshLayout.setRefreshing(false);
            }
        });
    }

    private void abIndexProjectList() {
        Call<ResultDO<List<IndexProject>>>  call = ApiClient.getApiAdapter().AbIndexProjectList(memberId);
        call.enqueue(new Callback<ResultDO<List<IndexProject>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<IndexProject>>> call, Response<ResultDO<List<IndexProject>>> response) {
                if (response.body() == null || isFinish) {
                    return;
                }
                refreshLayout.setRefreshing(false);
                if (response.body().getCode() == 0 && response.body().getResult() != null) {
                    projectList.clear();
                    projectList.addAll(response.body().getResult());
                    for (IndexProject indexProject:projectList){
                        if (indexProject.getList()!=null){
                            indexProject.setHaveHeader(false);
                        }else {
                            indexProject.setHaveHeader(true);
                        }
                    }
                    adapter.notifyDataSetChanged();
                } else {
                    ToastUtils.showToast(mContext, response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO<List<IndexProject>>> call, Throwable t) {
                if (isFinish) {
                    return;
                }
                refreshLayout.setRefreshing(false);
            }
        });
    }

    private void loading(){
        if (!refreshLayout.isRefreshing()){
            refreshLayout.setRefreshing(true);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }
}
